package com.binguo.common.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;


/**
 * 短信http接口的java代码调用示例
 * 基于Apache HttpClient 4.3
 *
 * @author songchao
 * @since 2015-04-03
 */
public class JavaSmsApi {
    private static Logger logger = LoggerFactory.getLogger(JavaSmsApi.class);

    // 模板发送接口的http地址
    private static String URI_TPL_SEND_SMS = "http://yunpian.com/v1/sms/tpl_send.json";

    //编码格式。发送编码格式统一用UTF-8
    private static String ENCODING = "UTF-8";

    private static String apikey = "88f35b22ca3b752a56be6c72eac7d67c";//jay
//    private static String apikey = "d574e019e6a124dae21ce0e932b4ad11";//jay

    //短信默认模版:【#company#】您的验证码是#code#。如非本人操作，请忽略本短信
    private static int DEFAULT_TEMPLATE = 3121384;

    private static int RECHARGE_TEMPLATE = 3281338;

    private static int QUCANGUICODE_TEMPLATE = 3504060;

    //云片:存餐柜初次存入短信ID
    private static int QUCANGUICODE_CUNRU = 3679184;

    //云片:存餐柜商品被取出短信ID
    private static int QUCANGUICODE_QUCHU = 3679212;

    //云片:提醒用户取餐柜等待ID
    private static int QUCANGUICODE_DENGDAI = 3679196;

    //云片:取餐柜超时提醒用户ID
    private static int QUCANGUICODE_TIMEOUT = 3679204;

    //云片:取餐柜超时提醒商户ID
    private static int QUCANGUICODE_TIMEOUT_SHOP = 3679208;

    public static void main(String[] args) {
        try {
            sendQuCanGuiTimeoutShop("13588204717","13588204717","100","2019-10-11","测试");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * SMS code为0为正常发送成功
     * @param phone
     * @param code
     * @return
     */
    public static SMS sendVerify(String phone, String code){
        String result = null;
        try {
            result = JavaSmsApi.tplSendSms(code, phone);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        SMS smsResult = JacksonUtil.json2Bean(result, SMS.class);
        return smsResult;
    }

    /**
     * SMS code为0为正常发送成功
     * @param phone
     * @param rechargeMoney
     * @param shopName
     * @return
     */
    public static SMS sendRechargeVerify(String phone, String rechargeMoney,String shopName){
        String result = null;
        try {
            result = JavaSmsApi.sendRechargeSms(rechargeMoney,shopName, phone);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        SMS smsResult = JacksonUtil.json2Bean(result, SMS.class);
        return smsResult;
    }

    /**
     * SMS code为0为正常发送成功
     * @param phone
     * @param code
     * @param quCanGuiNum
     * @return
     */
    public static SMS sendQuCanGuiCodeVerify(String phone, String code,String quCanGuiNum){
        String result = null;
        try {
            result = JavaSmsApi.sendQuCanGuiCodeSms(code,quCanGuiNum, phone);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        SMS smsResult = JacksonUtil.json2Bean(result, SMS.class);
        return smsResult;
    }

    /**
     * SMS code为0为正常发送成功
     * @Description:取餐柜存入商品发送短信
     * @param phone 接受短信的手机号
     * @param code 取餐码
     * @param quCanGuiName 取餐柜名
     * @return
     */
    public static SMS sendQuCanGuiCodeVerifyNew(String phone, String code,String quCanGuiName){
        String result = null;
        try {
            result = JavaSmsApi.sendQuCanGuiCodeSmsNew(code,quCanGuiName, phone);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject resultJson = JSON.parseObject(result);
        String resultCode = resultJson.getString("code");
        if (!resultCode.equals("0")){
            logger.error("短信发送失败:"+result);

        }
        SMS smsResult = JacksonUtil.json2Bean(result, SMS.class);
        return smsResult;
    }

    /**
     * SMS code为0为正常发送成功
     * @Description:取餐柜取出商品发送短信
     * @param phone 接受短信的手机号
     * @param code 取餐码
     * @param quCanGuiName 取餐柜名
     * @return
     */
    public static SMS sendQuCanGuiQuchu(String phone, String code,String quCanGuiName){
        String result = null;
        try {
            result = JavaSmsApi.sendQuCanGuiQuchuSms(code,quCanGuiName, phone);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject resultJson = JSON.parseObject(result);
        String resultCode = resultJson.getString("code");
        if (!resultCode.equals("0")){
            logger.error("短信发送失败:"+result);

        }
        SMS smsResult = JacksonUtil.json2Bean(result, SMS.class);
        return smsResult;
    }

    /**
     * SMS code为0为正常发送成功
     * @Description:取餐柜超时提醒用户发送短信
     * @param phone 接受短信的手机号
     * @param code 取餐码
     * @param time 等待时间
     * @param shopPhone 商户联系手机号
     * @param quCanGuiName 取餐柜名
     * @return
     */
    public static SMS sendQuCanGuiTimeout(String phone,
                                          String shopPhone,
                                          String code,
                                          String time,
                                          String quCanGuiName){
        String result = null;
        try {
            result = JavaSmsApi.sendQuCanGuiTimeoutSms(shopPhone,code,time,quCanGuiName,phone);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject resultJson = JSON.parseObject(result);
        String resultCode = resultJson.getString("code");
        if (!resultCode.equals("0")){
            logger.error("短信发送失败:"+result);
        }
        SMS smsResult = JacksonUtil.json2Bean(result, SMS.class);
        return smsResult;
    }

    /**
     * SMS code为0为正常发送成功
     * @Description:取餐柜定时任务发送通知短信
     * @param phone 接受短信的手机号
     * @param code 取餐码
     * @param time 等待时间
     * @param quCanGuiName 取餐柜名
     * @return
     */
    public static SMS sendQuCanGuiDengDai(String phone,
                                          String code,
                                          String time,
                                          String quCanGuiName){
        String result = null;
        try {
            result = JavaSmsApi.sendQuCanGuiDengDaiSms(code,time,quCanGuiName,phone);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject resultJson = JSON.parseObject(result);
        String resultCode = resultJson.getString("code");
        if (!resultCode.equals("0")){
            logger.error("短信发送失败:"+result);
        }
        SMS smsResult = JacksonUtil.json2Bean(result, SMS.class);
        return smsResult;
    }

    /**
     * SMS code为0为正常发送成功
     * @Description:取餐柜超时提醒商户发送短信
     * @param phone 接受短信的手机号
     * @param code 取餐码
     * @param time 等待时间
     * @param customerPhone 用户联系手机号码
     * @param quCanGuiName 取餐柜名
     * @return
     */
    public static SMS sendQuCanGuiTimeoutShop(String phone,
                                              String customerPhone,
                                              String code,
                                              String time,
                                              String quCanGuiName){
        String result = null;
        try {
            result = JavaSmsApi.sendQuCanGuiTimeoutShopSms(customerPhone,code,time,quCanGuiName,phone);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject resultJson = JSON.parseObject(result);
        String resultCode = resultJson.getString("code");
        if (!resultCode.equals("0")){
            logger.error("短信发送失败:"+result);
        }
        SMS smsResult = JacksonUtil.json2Bean(result, SMS.class);
        return smsResult;
    }

    /**
     * 通过模板发送短信(不推荐)
     *
     * @param code 　模板变量值
     * @param mobile    　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */
    public static String tplSendSms(String code, String mobile) throws Exception {
        String tpl_value2 = URLEncoder.encode("#code#",ENCODING) +"="
                + URLEncoder.encode(code, ENCODING);

        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(DEFAULT_TEMPLATE));
        params.put("tpl_value", tpl_value2);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

    public static String sendRechargeSms(String rechargeMoney,String shopName, String mobile) throws Exception {
        String tpl_value2 = URLEncoder.encode("#shop#",ENCODING) +"="
                + URLEncoder.encode(shopName, ENCODING)+"&"
                + URLEncoder.encode("#content#",ENCODING) + "="
                + URLEncoder.encode(rechargeMoney,ENCODING);;

        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(RECHARGE_TEMPLATE));
        params.put("tpl_value", tpl_value2);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

    public static String sendQuCanGuiCodeSms(String code,String quCanGuiNum, String mobile) throws Exception {
        String tpl_value2 = URLEncoder.encode("#code#",ENCODING) +"="
                + URLEncoder.encode(code, ENCODING)+"&"
                + URLEncoder.encode("#number#",ENCODING) + "="
                + URLEncoder.encode(quCanGuiNum,ENCODING);

        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(QUCANGUICODE_TEMPLATE));
        params.put("tpl_value", tpl_value2);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }



    public static String sendQuCanGuiCodeSmsNew(String code,String quCanGuiName, String mobile) throws Exception {
        String tpl_value2 = URLEncoder.encode("#code#",ENCODING) +"="
                + URLEncoder.encode(code, ENCODING)+"&"
                + URLEncoder.encode("#name#",ENCODING) + "="
                + URLEncoder.encode(quCanGuiName,ENCODING);

        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(QUCANGUICODE_CUNRU));
        params.put("tpl_value", tpl_value2);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

    public static String sendQuCanGuiQuchuSms(String code,String quCanGuiName, String mobile) throws Exception {
        String tpl_value2 = URLEncoder.encode("#code#",ENCODING) +"="
                + URLEncoder.encode(code, ENCODING)+"&"
                + URLEncoder.encode("#name#",ENCODING) + "="
                + URLEncoder.encode(quCanGuiName,ENCODING);

        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(QUCANGUICODE_QUCHU));
        params.put("tpl_value", tpl_value2);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

    public static String sendQuCanGuiDengDaiSms(String code,
                                                String time,
                                                String quCanGuiName,
                                                String mobile) throws Exception {
        String tpl_value2 = URLEncoder.encode("#time#",ENCODING) +"="
                + URLEncoder.encode(time, ENCODING)+"&"
                + URLEncoder.encode("#name#",ENCODING) + "="
                + URLEncoder.encode(quCanGuiName,ENCODING) +"&"
                + URLEncoder.encode("#code#",ENCODING) + "="
                + URLEncoder.encode(code,ENCODING);

        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(QUCANGUICODE_DENGDAI));
        params.put("tpl_value", tpl_value2);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

    public static String sendQuCanGuiTimeoutSms(String shopPhone,
                                                String code,
                                                String time,
                                                String quCanGuiName,
                                                String mobile) throws Exception {
        String tpl_value2 = URLEncoder.encode("#time#",ENCODING) +"="
                + URLEncoder.encode(time, ENCODING)+"&"
                + URLEncoder.encode("#phone#",ENCODING) + "="
                + URLEncoder.encode(shopPhone,ENCODING)+"&"
                + URLEncoder.encode("#name#",ENCODING) + "="
                + URLEncoder.encode(quCanGuiName,ENCODING)+"&"
                + URLEncoder.encode("#code#",ENCODING) + "="
                + URLEncoder.encode(code,ENCODING);

        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(QUCANGUICODE_TIMEOUT));
        params.put("tpl_value", tpl_value2);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

    public static String sendQuCanGuiTimeoutShopSms(String customerPhone,
                                                    String code,
                                                    String time,
                                                    String quCanGuiName,
                                                    String mobile) throws Exception {
        String tpl_value2 = URLEncoder.encode("#phone#",ENCODING) +"="
                + URLEncoder.encode(customerPhone, ENCODING)+"&"
                + URLEncoder.encode("#time#",ENCODING) + "="
                + URLEncoder.encode(time,ENCODING)+"&"
                + URLEncoder.encode("#name#",ENCODING) + "="
                + URLEncoder.encode(quCanGuiName,ENCODING)+"&"
                + URLEncoder.encode("#code#",ENCODING) + "="
                + URLEncoder.encode(code,ENCODING);

        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(QUCANGUICODE_TIMEOUT_SHOP));
        params.put("tpl_value", tpl_value2);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }


    /**
     * 通过模板发送短信(不推荐)
     *
     * @param code 　模板变量值
     * @param mobile    　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */
    public static String tplSendSms2(String code, String mobile) throws Exception {
        String tpl_value2 = URLEncoder.encode("#code#",ENCODING) +"="
                + URLEncoder.encode(code, ENCODING) + "&"
                + URLEncoder.encode("#company#",ENCODING) + "="
                + URLEncoder.encode("云澎AI",ENCODING);

        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(DEFAULT_TEMPLATE));
        params.put("tpl_value", tpl_value2);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }


    public static String post(String url, Map < String, String > paramsMap) {
        CloseableHttpClient client = org.apache.http.impl.client.HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList <
                        NameValuePair > ();
                for (Map.Entry < String, String > param: paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(),
                            param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList,
                        ENCODING));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity, ENCODING);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseText;
    }
}